﻿using System;
using System.IO;
using RSuite.Services;

namespace RSuite.R2.Services
{
    public class MainWebService: WebServiceBase
    {
        protected override object Process(string method, dynamic parameters)
        {
            switch (method)
            {
                case "open":
                    return this.Open(parameters);
                case "save":
                    return this.Save(parameters["id"], parameters["data"]);
                default:
                    return null;
            }
        }

        private object Open(string id)
        {
            var path = this.GetReviewPath(id);
            if (!File.Exists(path))
            {
                return new
                {
                    errCode = 1,
                    errMsg = "Id not found"
                };
            }
            else
            {
                return new
                {
                    id = id,
                    data = File.ReadAllText(path)
                };
            }
        }

        private object Save(string id, string data)
        {
            if (string.IsNullOrEmpty(id))
            {
                id = string.Format("{0:yyyyMMdd HHmmss}", DateTime.Now);
            }
            File.WriteAllText(this.GetReviewPath(id), data);
            return id;
        }

        private string GetReviewPath(string id)
        {
            return new FileInfo(string.Format(@"Reviews\{0}.rvw", id)).FullName;
        }
    }
}